package com.seedeer.common.util;

import com.seedeer.common.constant.ProfileConsts;
import com.seedeer.pms.model.PmsAccountInfo;
import com.seedeer.pms.service.PmsOpenService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: bbc
 * @description:
 * @author: Mr.Wang
 * @create: 2020-04-24 10:05
 **/
@Component
public class AuthorityUtils {

    private final static Logger logger = LoggerFactory.getLogger(AuthorityUtils.class);

    @Autowired
    private PmsOpenService openService;

    @Autowired
    private Environment env;

    private static PmsOpenService pmsOpenService;

    private static Environment environment;

    @PostConstruct
    public void init() {
        this.pmsOpenService = openService;
        this.environment = env;
    }


    public static PmsAccountInfo getCurrentUser() {
        try {
            if (environment.acceptsProfiles(ProfileConsts.DEV)) {
                PmsAccountInfo pmsAccountInfo = new PmsAccountInfo();
                pmsAccountInfo.setUserCode("sdtest");
                pmsAccountInfo.setUserName("sdtest");
                return pmsAccountInfo;
            }
            return pmsOpenService.fetchAccountInfo();
        } catch (Exception e) {
            logger.error("获取当前登录用户异常", e);
        }
        return null;
    }

    public static List<String> getOrgCodes() {
        List<String> orgCodes = null;
        PmsAccountInfo pmsAccountInfo = getCurrentUser();
        if (null != pmsAccountInfo) {
            List<PmsAccountInfo.OrgInfo> orgInfos = pmsAccountInfo.getOrgInfos();
            if (CollectionUtils.isNotEmpty(orgInfos)) {
                orgCodes = orgInfos.stream().map(PmsAccountInfo.OrgInfo::getOrgCodes)
                        .flatMap(Collection::stream)
                        .collect(Collectors.toList());
            }
        }
        return orgCodes;
    }

}
